#!/bin/bash
set -e
# 读取公共常量配置参数 GITLAB_URL + ACCESS_TOKEN + PROJECT_PATHS
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.sh"

# Parameters
ISSUE_IDS="$1" # 格式: #274#275

# Validate input
if [ ${#PROJECT_PATHS[@]} -eq 0 ] || [ -z "$ISSUE_IDS" ] || [ -z "$ACCESS_TOKEN" ]; then
  echo "Usage: $0 <issue-ids: #1#2#3>"
  exit 1
fi

command -v curl >/dev/null 2>&1 || {
  echo >&2 "Error: curl required but not installed."
  exit 1
}

# 解析 issue id：去掉前后 #，按 # 分割
IFS="#" read -ra ISSUE_ARRAY <<<"$ISSUE_IDS"

# 遍历所有 issue id
for iid in "${ISSUE_ARRAY[@]}"; do
  echo "Checking issue #$iid..."
  if [ -z "$iid" ]; then
    continue
  fi

  issue_found=false

  for project_path in "${PROJECT_PATHS[@]}"; do
    encoded_project_path=$(jq -rn --arg x "$project_path" '$x|@uri')
    response_file=$(mktemp)
    status_code=$(curl -s -w "%{http_code}" -o "$response_file" \
      -H "PRIVATE-TOKEN: $ACCESS_TOKEN" \
      "${GITLAB_URL}/api/v4/projects/${encoded_project_path}/issues/${iid}")

    if [ "$status_code" -eq 200 ]; then
      echo "✅ Issue #$iid exists in project $project_path."
      issue_found=true
      rm -f "$response_file"
      break
    fi

    rm -f "$response_file"
  done

  if [ "$issue_found" = false ]; then
    echo "❌ Issue #$iid not found in any configured project path."
    exit 1
  fi
done

echo "🎉 All issues exist in at least one project path."
